package itemdb

import (
	"SystemExploration/ability"
	"SystemExploration/mongodb/log"
	"github.com/robfig/cron"
	"time"
)

type ItemInfo struct {
	Name    string   //任务名称
	Machine string   //机器人
	Crons   string   //任务表达式 时间格式
	Url     string   //探测地址
	People  []string //通知人列表
	State   int64    //任务状态
	Type    int64    //任务类型 1-ping 2 数据库 3 ...
}

type TaskItem struct {
	Taskinfo ItemInfo
	TaskCron *cron.Cron
}

func NewItemTask(items ItemInfo) *TaskItem {
	item := &TaskItem{
		Taskinfo: items,
		TaskCron: cron.New(),
	}
	return item
}

func (t *TaskItem) Init() {
	_ = t.TaskCron.AddFunc(t.Taskinfo.Crons, func() {
		pinginfo := ability.PingUrl{
			Name:    t.Taskinfo.Name,
			Machine: t.Taskinfo.Machine,
			Url:     t.Taskinfo.Url,
			People:  t.Taskinfo.People,
		}
		ping := ability.NewPing(pinginfo)
		str, t2 := ping.Ping()
		loginfo := &log.Tasklog{
			TaskName:  t.Taskinfo.Name,
			AddTime:   time.Now(),
			Consuming: t2,
			Result:    str,
		}
		_ = log.AddLogOne(loginfo)
	})
}

func (t *TaskItem) Run() {
	t.TaskCron.Start()
}

func (t *TaskItem) Stop() {
	t.TaskCron.Stop()
}
